<?php
/**
  * Mar 4, 2008
  *
  * Coded by: Ropu
  *
  */

require_once 'classes/dao/appVersionDAO.php';
class AppVersion {
  private $id = null;
  private $url;
  private $uploaded=1;
  private $date;
  private $version;
  private $public=1;
  private $openSource=1;
  
  public function __construct($id=null) {
    if(!is_null($id)) {
      $this->id = $id;
      $this->id = AppVersionDAO::get($this);
    }
  }
  
  /*
   * Getters
   */

  public function getId(){
    return $this->id;
  }

  public function getUrl(){
    return $this->url;
  }
  
  public function isUploaded(){
    return $this->uploaded;
  }
  
  public function getDate(){
    return $this->date;
  }
  
  public function getVersion(){
    return $this->version;
  }
  
  public function isPublic(){
    return $this->public;
  }
  
  public function isOpensource(){
    return $this->openSource;
  }
  
/*
 * Setters
 */
  
  public function setUrl($url) {
    $this->url = $url;
  }
  
  public function setUploaded($uploaded) {
    $this->uploaded = $uploaded;
  }
  
  public function setDate($date) {
    $this->date = $date;
  }
  
  public function setVersion($version) {
    $this->version = $version;
  }
  
  public function setPublic($public) {
    $this->public = $public;
  }
  
  public function setOpensource($opensource) {
    $this->openSource = $opensource;
  }
  
  public function upload($file) {
    if($file['error']){
      throw new FileException('Error uploading file', $file['error']); 
    }
    if(!$this->checkMIMEType($file['type'])) {
      throw new FileException('Invalid image type: ' . $file['type']);
    }
    
    $rand_name = time() . "_" . $this->version . "_" . substr($file['name'], 0, strpos($file['name'], '.')-1);
    $new_fs_path = APPS_FS_DIR . $rand_name . '.xml';
    $new_ws_path = APPS_WS_DIR . $rand_name . '.xml';
    if(move_uploaded_file($file['tmp_name'], $new_fs_path)) {
      Log::medium('Fail to move file: ' . $file['tmp_name'] . " to " . $new_fs_path);
      $this->url = $new_ws_path;
    } else {
      throw new FileException('Error Uploading file!');
    }
    return true;
  }
  
  private function checkMIMEType($mime=false) {
    $this->MIMEType = $mime?strtolower($mime):strtolower($this->MIMEType);
    switch($this->MIMEType){
        // xml
      case 'application/xml':
      case 'text/xml':
      case 'application/xhtml+xml':
        return true;
        break;
      default:
        return false;
        break;
    }
  }
  
  
}

class FileException extends Exception {
  
}
